package com.example.util;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Slf4j
public class DateUtils {
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final String YYYYMMDD1 = "yyyy-MM-dd";//
    public static final String YYYYMMDDHHMMSS1 = "yyyy-MM-dd HH:mm:ss";

    /**
     * 按自定义日期格式格式化日期
     *
     * @param target
     * @param format
     * @return 格式化后的日期字符串，如果传入的日期对象为NULL，返回空字符串
     */

    public static String formatDate(String target, String format) {
        if (target == null) {
            return "";
        }
        return target;
    }

    /**
     * 当前时间字符串
     */
    public static String dateToString() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss").toString();
    }

    public static String todayString() {
        return formatDate(new Date(), YYYYMMDD);
    }

    public static String formatDate(Date target, String format) {
        if (target == null) {
            return "";
        }
        return new SimpleDateFormat(format).format(target);
    }

    public static Timestamp parseDate(String date, String format) throws ParseException {
        return new Timestamp(new SimpleDateFormat(format).parse(date).getTime());
    }

    public static String formatDate(String date, String fromFormat, String toFormat) throws ParseException {
        if (date == null || date.trim().length() == 0) {
            return null;
        }
        return formatDate(parseDate(date, fromFormat), toFormat);
    }

    public static String formateTimestame(String d) {
        if (d.contains(".")) {
            d = d.substring(0, d.lastIndexOf("."));
        }
        return d;
    }

    public static long calculateTimeDifference(String date1, String date2) throws ParseException {
        return parseDate(date2, YYYYMMDDHHMMSS1).getTime() - parseDate(date1, YYYYMMDDHHMMSS1).getTime();
    }

    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }

    public static String formatTimeLongToStr(Long time, Long split) {
        return String.valueOf(time / split);
    }

    public static String formatHourDisplay(String hour) {
        try {
            Timestamp time = parseDate(hour, "yyyy-MM-dd HH");
            return formatDate(time, "yyyy-MM-dd HH:mm") + "-"
                    + formatDate(new Timestamp(time.getTime() + 3600000), "HH:mm");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return "";
        }
    }

    public static String getDate(String str) {
        return str.substring(0, 10);
    }

    /**
     * 将String 类型的秒数  转换为  HH:mm:ss  类型
     *
     * @param time
     * @return
     */
    public static String parseString2DateString(String time) {
        long ms = Integer.parseInt(time) * 1000;//毫秒数
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        return formatter.format(ms);
    }

    /**
     * 时间转换成秒数
     *
     * @param time
     * @return
     */
    public static Integer parseString2TimeInteger(String time) {
        String[] split = time.split(":");
        Integer s = Integer.parseInt(split[0]) * 3600; //小时
        s += Integer.parseInt(split[1]) * 60; //分钟
        s += Integer.parseInt(split[2]); //秒
        return s;
    }

    /**
     * 两个时间相差秒数
     *
     * @param a 时间参数 1 格式：1990-01-01 12:00:00
     * @param b 时间参数 2 格式：2009-01-01 12:00:00
     * @return long
     */
    public static long getDistanceTimes(Date a, Date b) {
        long interval = (b.getTime() - a.getTime()) / 1000;
        return interval;
    }

    /**
     * 获取两个日期的间隔天数
     * @param a
     * @param b
     * @return
     */
    public static long getDistanceDay(Date a, Date b) {
        long interval =  (b.getTime() - a.getTime()) / (1000 * 60 * 60 *24);
        return interval;
    }

    /**
     * 获取本周第一天的日期
     *
     * @return
     */
    public static Date getCurrWeekFirst() {
        Calendar cal = Calendar.getInstance();
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    /**
     * 获取本月第一天的日期
     *
     * @return
     */
    public static Date getCurrMonthFirst() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        return cal.getTime();
    }
    /**
     * 获取本月最后一天的日期
     *
     * @return
     */
    public static Date getCurrMonthLast(){
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        return ca.getTime();
    }

    /**
     * 获取本季度第一天
     *
     * @return
     */
    public static Date getCurrQuarterFirst() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取本年第一天
     *
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    private static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 报表日期格式化
     *
     * @param source
     * @param format
     * @return
     */
    public static String formatStatDate(String source, String format) {
        if (StringUtils.isNotBlank(source)) {
            source = source.trim();
            if (source.length() <= format.length())
                return source;
            return source.substring(0, format.length());
        }
        return "";
    }

    /**
     * 当天日期近1个月的日期列表
     * @return
     */
    public static List<String> getDates() {
        List<String> dates = new ArrayList<>();
        LocalDate now = LocalDate.now();
        LocalDate past = now.minus(30, ChronoUnit.DAYS);
        while (!now.isBefore(past)) {
            dates.add(past.toString());
            past = past.plusDays(1L);
        }
        return dates;
    }

    public static Date getStartDate(Date date){
        Calendar start = Calendar.getInstance();
        start.setTime(date);
        start.set(Calendar.HOUR, 0);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);
        start.set(Calendar.MILLISECOND, 0);
        return start.getTime();
    }

    public static Date getEndTime(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * 主方法的测试
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(formatDate(getCurrWeekFirst(), YYYYMMDD1));
        System.out.println(formatDate(getCurrMonthFirst(), YYYYMMDD1));
        System.out.println(formatDate(getCurrQuarterFirst(), YYYYMMDD1));
        System.out.println(formatDate(getCurrYearFirst(), YYYYMMDD1));
    }

}
